<template>
  <a-modal
    :title="formTile + '消息发送模板任务'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card style="background:rgb(232, 232, 232)">
        <a-row
          type="flex"
          justify="start"
          align="top"
        >
          <a-col :span="24">
            <a-form
              :form="form"
              @submit="handleSubmit"
              :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol"
            >
              <div style="background: #fff;padding: 30px 0;">
                <a-form-item
                  label="消息模板"
                  :required="true"
                >
                  <a-select
                    allow-clear
                    show-search
                    placeholder="请选择消息模板"
                    @change="changeTemplate"
                    optionFilterProp="children"
                    v-decorator="[
                  'id',
                  {
                    rules: [{ required: true, message: '请选择消息模板!' }]
                  }
                ]"
                  >
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in templateList"
                      :key="index"
                    >
                      {{ item.templateName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="任务名称"
                  :required="true"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入任务名称"
                    :maxLength="40"
                    v-decorator="[
                  `taskName`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入任务名称！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>
                <a-form-item
                  label="执行策略"
                  :required="true"
                >
                  <a-select
                    allow-clear
                    show-search
                    placeholder="请选择执行策略"
                    @change="changeTime"
                    optionFilterProp="children"
                    v-model="taskType"
                  >
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in typeList"
                      :key="index"
                    >
                      {{ item.title }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-model-item
                  label="执行时间"
                  v-if="taskType == 2"
                  :required="true"
                >
                  <j-cron v-model="cronExpression"></j-cron>
                </a-form-model-item>
                <a-form-item
                  v-if="taskType == 1"
                  label="执行时间"
                  :required="true"
                >

                  <a-date-picker
                    show-time
                    placeholder="请选择执行时间"
                    @change="selectTime"
                    :disabled-date="disabledDate"
                    :disabled-time="disabledDateTime"
                    v-model="executeNewTime"
                  />

                </a-form-item>
              </div>
              <div style="background: #fff;padding: 30px 0px 10px;margin-top: 20px;">
                <a-form-item label="发送消息模板">
                  <a-row :gutter="16">
                    <div
                      class="text"
                      style="white-space: pre-line;line-height: 25px;"
                    >
                      <span
                        v-if="example"
                        style="position: relative;top: -30px;"
                      >
                        {{example}}
                      </span>
                      <span
                        v-else
                        style="color: #ee0a24;font-size:17px"
                      >
                        请选择模版消息ID
                      </span>
                    </div>

                  </a-row>

                </a-form-item>
              </div>
              <div style="background: #fff; padding-top: 30px;margin-top: 20px;">
                <a-form-item label="任务描述">
                  <a-input
                    allow-clear
                    placeholder="请输入任务描述"
                    :maxLength="40"
                    v-decorator="[
                  `taskDesc`,
                  {
                    validateTrigger: ['change', 'blur'],
                  }
                ]"
                  />
                </a-form-item>
                <a-form-item
                  label="备注"
                  :required="true"
                >
                  <a-textarea
                    allow-clear
                    placeholder="请输入备注"
                    :rows="4"
                    v-decorator="['remark', { rules: [{ required: true, message: '请输入备注' }] }]"
                  ></a-textarea>
                </a-form-item>
                <a-form-item
                  label="消息群发对象"
                  :required="true"
                  style="display:flex;flex-direction: row;"
                >
                  <a-select
                    allow-clear
                    style="width:50%;"
                    show-search
                    placeholder="请选择类型"
                    @change="changeType"
                    optionFilterProp="children"
                    v-model="userType"
                  >
                     <!-- <a-select-option
                      :value="item.value"
                      v-for="(item,index)  in dictList"
                      :key="index"
                    >
                      {{ item.name }}
                    </a-select-option> -->
                     <a-select-opt-group
                      v-for="(item,index)  in dictList"
                      :key="index"
                    >
                     <span slot="label" style="color:#faad14;font-size:15px">{{item.label}}</span>
                      <a-select-option
                        :value="subitem.value"
                        v-for="(subitem,index)  in item.options"
                        :key="index"
                      >
                        {{subitem.label}}
                      </a-select-option>
                    </a-select-opt-group>
                  </a-select>
                  <a-select
                    allow-clear
                    v-if="userType==1"
                    style="width:48%;margin-left:2%"
                    show-search
                    placeholder="请选择消息群发对象"
                    optionFilterProp="children"
                    @change="changeLabel"
                    v-model="userBusinessId"
                  >
                    <a-select-option :value="0">
                      全部
                    </a-select-option>
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in groupList"
                      :key="index"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                   <a-select
                    allow-clear
                    v-if="userType==3"
                    style="width:48%;margin-left:2%"
                    show-search
                    placeholder="请选择人群包"
                    optionFilterProp="children"
                    v-model="userBusinessId"
                  >
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in bagList"
                      :key="index"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                   <a-select
                    allow-clear
                    v-if="userType==33"
                    style="width:48%;margin-left:2%"
                    show-search
                    placeholder="请选择人群划分"
                    optionFilterProp="children"
                    v-model="userBusinessId"
                  >
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in personList"
                      :key="index"
                    >
                      {{ item.peopleName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <div style="width:90%;display:flex;margin: auto;">
                  <a-textarea
                    style="margin-bottom:20px"
                    allow-clear
                    v-if="userType==2"
                    :rows="3"
                    placeholder="请输入openID,多个openID使用英文逗号（，）分隔"
                    v-model="openid"
                  ></a-textarea>
                  <!-- :row-selection="{ selectedRowKeys: selectedRowKeys,selectedRows:selectedRows, onChange: onSelectChange}" -->
                  <a-table
                    bordered
                    v-if="userType==1"
                    style="width:100%"
                    :loading="loading"
                    :pagination="pagination"
                    :columns="columns"
                    :data-source="dataSource"
                    @change="handleTableChange"
                    :scroll="{ x: true }"
                  >
                    <!-- <template
                      slot="action"
                      slot-scope="txt, record"
                    >
                      <a
                        class="mr-10"
                        @click="add(record)"
                      >
                        <a-icon type="edit" />编辑
                      </a>
                      <a
                        class="mr-10"
                        @click="deleteRecord(record)"
                      >
                        <a-icon type="delete" />删除
                      </a>
                    </template> -->
                  </a-table>
                </div>

              </div>
              <a-row style="margin-top:10px">
                <a-col
                  :span="16"
                  :offset="18"
                  class="info-action"
                >
                  <a-button @click="clear">
                    重置
                  </a-button>
                  <a-button
                    :style="{ marginLeft: '8px' }"
                    type="primary"
                    :loading="bloading"
                    html-type="submit"
                  >
                    保存
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
import moment from 'moment'
import 'moment/locale/zh-cn'
const columns = [
  {
    title: '昵称',
    dataIndex: 'nickname'
  },
  {
    title: 'open_id',
    dataIndex: 'openid'
  },
  {
    title: '时间',
    dataIndex: 'createTime'
  }
  // {
  //   title: '操作',
  //   width: 150,
  //   scopedSlots: { customRender: 'action' }
  // }
]
const typeList = [
  {
    id: 1,
    title: '特定时间点执行执行一次'
  },
  {
    id: 2,
    title: '周期执行'
  }
]
export default {
  props: {
    news: {
      type: Object,
      default: null
    },
    appid: {
      type: String,
      default: null
    },
    menuName:{
      type: String,
      default: null
    }
  },

  data() {
    return {
      columns,
      urlKey: 'basemgt-wx',
      templateList: [],
      typeList,
      menuList: [],
      example: '',
      groupList: [],
      templateId: '',
      templateName: '',
      dataSource: [],
      dictList:[],
      bagList:[],
      bag:undefined,
      content: '',
      openid: '',
      cronExpression: '',
      taskType: 1,
      userRecordList: [],
      time: '',
      // selectedRowKeys: [],
      // selectedRows: [],
      executeNewTime: '',
      userType: '2',
      id: '',
      personList:[],
      userBusinessId: undefined,
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 16 },
          xs: { span: 12 },
          sm: { span: 12 }
        }
      },
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: total => `共 ${total} 条记录`,
        itemRender: (current, type, originalElement) => {
          if (type === 'prev') {
            return <a>上一页</a>
          } else if (type === 'next') {
            return <a>下一页</a>
          }
          return originalElement
        }
      },
      add: false,
      loading: false,
      bloading: false,
      templateId: '',
      title: '',
      form: this.$form.createForm(this)
    }
  },
  created() {
    const { news } = this.$props
    console.log(news)
    if (news) {
      this.formTile = '编辑'
      this.id = news.id
      const executeTimeParam = JSON.parse(news.executeTimeParam)
      this.taskType = news.taskType
      this.cronExpression = news.jobCron
      this.userBusinessId = Number(news.userBusinessId)
      this.userType = news.userType +''
      this.$nextTick(() => {
        this.form.setFieldsValue({
          id: news.myTemplateId,
          taskName: news.taskName,
          executeNewTime: news.executeNewTime,
          taskDesc: news.taskDesc,
          remark: news.remark
        })
      })
      this.getDetail()
      this.getTime(executeTimeParam.executeNewTime)
      this.changeTemplate(news.myTemplateId)
    } else {
      this.formTile = '新增'
      this.add = true
    }
  },
  watch: {
    appid() {
      this.getMenuList()
      this.getGroupList()
      this.getPersonList()
      this.getTypeList()
      this.getBagList()
      this.getNewPersonList()
    }
  },
  mounted() {
    this.getMenuList()
    this.getGroupList()
    this.getPersonList()
    this.getTypeList()
      this.getBagList()
      this.getNewPersonList()

  },
  methods: {
    disabledDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day')
    },
    range(start, end) {
      const result = []
      for (let i = start; i < end; i++) {
        result.push(i)
      }
      return result
    },
    disabledDateTime() {
      let nowHour = new Date().getHours()
      return {
        disabledHours: () => this.range(0, nowHour)
      }
    },

    reset() {
      this.form.resetFields()
      this.taskType = ''
      this.cronExpression = ''
      this.userBusinessId = ''
      this.userType = ''
      this.executeNewTime = ''
      this.$emit('close')
    },
    clear() {
      this.form.resetFields()
    },
    getTime(time) {
      var date = new Date(time)
      var Y = date.getFullYear() + '-'
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
      var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
      var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      this.executeNewTime = Y + M + D + h + m + s
    },
    getDetail() {
      const params = {
        id: this.id
      }
      try {
        getAction(`${this.urlKey}/WxTemplateTask/findWxTemplateTaskDetailById`, params).then(data => {
          if (data.code == 200) {
            this.templateList = data.data
            this.userRecordList = data.data.userRecordList
            if (this.userType == 2 && this.userRecordList.length) {
              const arr = []
              this.userRecordList.map(item => {
                arr.push(item.openid)
              })
              this.openid = arr.toString()
            }
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning(error.msg)
      }
    },
    getMenuList() {
      const params = {
        appid: this.appid
      }
      try {
        postAction(`${this.urlKey}/WxMyTemplate/findWxMyTemplateList`, params).then(data => {
          if (data.code == 200) {
            this.templateList = data.data
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning(error.msg)
      }
    },
    selectTime(date, dateString) {
      this.executeNewTime = dateString
    },
    handleTableChange(pagination) {
      this.pagination = pagination
      this.loadData()
    },
    changeTemplate(value) {
      const params = {
        id: value
      }
      getAction(`${this.urlKey}/WxMyTemplate/findWxMyTemplateDetailById`, params).then(data => {
        if (data.code == 200) {
          this.example = data.data.messageResult.replace(/(^\s*)/g, '')
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    changeTime(time) {
      if (time == 1) {
        this.cronExpression = ''
      } else {
        this.executeNewTime = ''
      }
    },
    getBagList(){
      const params = {
        type: 'WxDataInfo',
        parentId:18,
        appid:this.appid
      }
      try {
        postAction(`${this.urlKey}/WxDict/findWxDictList`, params).then(data => {
          if (data.code == 200) {
            this.bagList = data.data
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning("获取失败")
      }
    },
    getTypeList() {
      const params = {
        appid: this.appid,
        parentId:13
      }
      try {
        postAction(`${this.urlKey}/WxDict/findNewWxDictSelectList`, params).then(data => {
          if (data.code == 200) {
            this.dictList = data.data
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning("获取失败")
      }
    },
    getGroupList() {
      const params = {
        appid: this.appid
      }
      try {
        postAction(`${this.urlKey}/WxTagList/findWxTagListList`, params).then(data => {
          if (data.code == 200) {
            this.groupList = data.data
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning(error.msg)
      }
    },
    getPersonList() {
      const params = {
        appid: this.appid,
        pageSize: this.pagination.pageSize,
        pageNum: this.pagination.current,
        tagId: this.userBusinessId
      }
      try {
        postAction(`${this.urlKey}/WxUser/findUserInfoPageResultQuery`, params).then(data => {
          if (data.code == 200) {
            this.dataSource = data.data.records
            this.pagination.total = data.data.total
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning('获取列表失败')
      }
    },

     getNewPersonList() {
      const params = {
        businessid: 33,
      }
      try {
        postAction(`${this.urlKey}/managerPeopleRecord/findWxManagerPeopleRecordList`, params).then(data => {
          if (data.code == 200) {
            this.personList = data.data
            console.log( this.personList)
          } else {
            this.$message.warning(data.msg || data.message)
          }
        })
      } catch (error) {
        this.$message.warning('获取列表失败')
      }
    },
    // onSelectChange(selectedRowKeys, selectedRows) {
    //   this.selectedRowKeys = selectedRowKeys
    //   console.log(selectedRowKeys)
    //   this.selectedRows = selectedRows
    // },
    changeType(userType) {
      this.userType = userType
      this.userBusinessId = undefined
    },
    changeLabel(userBusinessId) {
      this.userBusinessId = userBusinessId
      this.getPersonList()
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
    },
    submit(values) {
      console.log(values)
      this.bloading = true
      const taskExecuteTimeParam = {
        executeNewTime: this.executeNewTime
      }
      let userRecordList = []
      if (this.userType == 2) {
        if(this.openid){
          let pathArr = this.openid.split(',')
        pathArr.map(item => {
          const WxUserRecordVo = {
            appid: this.appid,
            openid: item
          }
          userRecordList.push(WxUserRecordVo)
        })
        }
        
      } 
      // else {
        // this.selectedRows.map(item => {
        //   const WxUserRecordVo = {
        //     appid: this.appid,
        //     openid: item.openid,
        //     userId: item.id
        //   }
        //   userRecordList.push(WxUserRecordVo)
        // })
      // }
      this.templateList.map(item => {
        if (values.id == item.id) {
          ;(this.templateName = item.templateName), (this.templateId = item.templateId)
        }
      })
      var params = {
        id: this.id,
        myTemplateId: values.id,
        templateId: this.templateId,
        templateName: this.templateName,
        appid: this.appid,
        taskName: values.taskName,
        taskType: this.taskType,
        taskExecuteTimeParam: taskExecuteTimeParam,
        jobCron: this.cronExpression,
        taskDesc: values.taskDesc,
        remark: values.remark,
        userBusinessId: this.userBusinessId == 0 ? '' : this.userBusinessId,
        userType: this.userType,
        userRecordList: userRecordList
      }
      console.log(params)
      try {
        const api = this.add ? `${this.urlKey}/WxTemplateTask/insertWxTemplateTask` : `${this.urlKey}/WxTemplateTask/updateWxTemplateTask`
        postAction(api, params).then(data => {
          if (data.code == 200) {
            this.$message.success(this.add ? '新建成功！' : '修改成功！')
            this.bloading = false
            this.reset()
          } else {
            this.$message.warning(data.msg || data.message)
            this.bloading = false
          }
        })
      } catch (error) {
        this.$message.warning('保存失败！')
        this.bloading = false
      }
    }
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
  word-break: break-all;
  padding: 10px;
  margin: 10px;
  border: 1px dashed #969799;
}
</style>
